import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import recursion from '@/common/recursionForm';
import s from './style.module.css';
import { Dialog, Form, Radio, Confirm, Select, Button, Message } from '@knownsec/react-component';
import moment from 'moment';
import { exportTargets, exportPOST } from '~/API';
import { useHistory } from 'react-router-dom';
import { xorBy } from 'lodash';
import Datetime from '@knownsec/react-component/dist/Datetime';

import { getChapters as getChaptersApi } from '../../../../API/index';
export default function DateRangeSelect({ className, selTable, jobId, note, downBack, disabled }) {
  console.log('[ selTable ]-13', selTable);
  const defaultData = {
    job_ids: selTable,
    dateRange: [],
  };
  const history = useHistory();
  const [dialogVisible, setDialogVisible] = React.useState(false);
  const [downloadable, setDownloadable] = React.useState(true);
  const [jobList, setJobList] = useState([]);
  const [originalJob, setOriginalJob] = useState([]);
  const [form] = Form.useForm();
  const getAsset = async () => {
    const assetList = await exportTargets();
    const originalJob_ = [];
    const list = assetList.data.data.map((item) => {
      originalJob_.push({ ...item, value: item.target_id });
      return {
        label: `${item.target_url} ${item.target_name}`,
        labelHtml: `<span style="width: 250px;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.target_url}'>${item.target_url}</span>
					 <span style="width: 50px;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${item.target_name}'>${item.target_name}</span>
				 `,
        value: item.target_id,
      };
    });
    setOriginalJob(assetList.data.data);
    setJobList(list);
  };
  const onValues = (data) => {
    console.log('[ data ]-44', data);
    const values = recursion(data);
    console.log(values);
    if (values.hasOwnProperty('dateRange')) {
      if (!values.dateRange) {
        values.dateRange = [];
      }
    }
    form.current.setFieldsValue(values);
  };
  const validatormap = (rule, value = {}) => {
    if (rule.field === 'job_ids') {
      if (!value[0]) {
        return Promise.reject('请选择资产');
      }
    }
    return Promise.resolve();
  };
  const submitForm = () => {
    form.current.validateFields().then((data) => {
      if (!downloadable) return false;
      setDownloadable(false);
      const targets = [];
      originalJob.map((e) => {
        if (data.job_ids.includes(e.target_id)) {
          targets.push({
            target_id: e.target_id,
            target_url: e.target_url,
            target_name: e.target_name,
          });
        }
      });
      const timeDate =
        data.dateRange.length > 0
          ? {
              start_date: moment(data.dateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
              end_date: moment(data.dateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            }
          : {};
      console.log(timeDate, targets, data);
      exportPOST({
        targets,
        chapters: data.chapters,
        ...timeDate,
      })
        .then((res) => {
          if (res.status === 'success') {
            form.current.setFieldsValue(defaultData);
            form.current.resetFields();
            if (downBack) {
              downBack();
            } else {
              Confirm({
                title: '提示',
                pro: true,
                className: s.w400,
                message: <div className="confirmbox">正在导出报告，您可前往报告任务列表获取。</div>,
                onconfirm: () => {
                  history.push(`/down`);
                },
                oncancel: () => {},
              });
            }
          } else {
            Message.show({
              pro: true,
              showClose: false,
              type: 'error',
              message: '报告导出失败',
            });
          }
          setDownloadable(true);
          setDialogVisible(false);
        })
        .catch((e) => {
          setDownloadable(true);
          setDialogVisible(false);
          Message.show({
            pro: true,
            showClose: false,
            type: 'error',
            message: '报告导出失败',
          });
        });
    });
  };
  const disableDate = (current) => {
    return (
      current.diff(moment(), 'days', true) >= 0 ||
      current.diff(moment().subtract(180, 'days'), 'days', true) <= 0
    );
  };

  const [chapters, setChapters] = useState([]);
  const getChapters = async () => {
    try {
      const { data } = await getChaptersApi();
      console.log(data);
      setChapters(
        data.data.map((item, index) => {
          index = index + 1;
          return { value: index, label: item[index] };
        })
      );
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(async () => {
    getChapters();
  }, []);
  useEffect(() => {
    !disabled && getAsset();
  }, [disabled]);
  useEffect(() => {
    if (dialogVisible && jobId) {
      form.current.setFieldsValue({
        job_ids: [`${note}\t${jobId}`],
      });
    }
  }, [dialogVisible]);
  return (
    <div className={s.container}>
      <Button
        type="text"
        disabled={disabled}
        onClick={() => {
          form.current.setFieldsValue(defaultData);
          setDialogVisible(true);
          setDownloadable(true);
        }}
      >
        导出报告
      </Button>
      <Dialog
        className={s.w680}
        title="导出报告"
        visible={dialogVisible}
        onhide={() => {
          form.current.setFieldsValue(defaultData);
          form.current.resetFields();
          setDialogVisible(false);
        }}
        onsubmit={submitForm}
      >
        <div className={s.dcontent}>
          {/* <div className={s.tip}>已下载的历史报告默认存储一周。</div> */}
          <Form
            ref={form}
            initialValues={defaultData}
            onValuesChange={(newItem, allValues) => {
              onValues(newItem, allValues);
            }}
            labelCol={{ span: 4 }}
            labelAlign="right"
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              label="选择业务系统"
              name="job_ids"
              rules={[{ required: true, validator: validatormap }]}
              className={s.jobIds}
            >
              <Select
                checkAll
                placeholder="请选择业务系统"
                multiple
                className={cn(s.w500, s.dSelect)}
                option={jobList}
                clearable
                searchable
              />
            </Form.Item>
            <div className={s.pr}>
              <Form.Item label="时间范围" name="dateRange">
                <Datetime
                  disabledDate={disableDate}
                  onCalendarChange={(date) => {
                    if (date?.length > 0) {
                      form.current.setFieldsValue({ dateRange: date });
                    } else {
                      form.current.setFieldsValue({ dateRange: [] });
                    }
                  }}
                  ranges={{}}
                  className={s.w500}
                  dropdownClassName={s.z2002}
                />
              </Form.Item>
              <span className={s.dateTip}>若不选时间范围，则默认下载最新一次监测结果</span>
            </div>
            <Form.Item
              name="chapters"
              label="章节选择"
            >
              <Select
                className={cn(s.w500)}
                multiple
                allowClear
                option={chapters}
                placeholder="请选择章节"
              />
            </Form.Item>
          </Form>
        </div>
      </Dialog>
    </div>
  );
}

DateRangeSelect.propTypes = {
  className: PropTypes.string,
};

DateRangeSelect.defaultProps = {
  className: s.dateRangeSelect,
};
